<template>
  <div class="createPost-container">
    <el-form class="form-container" :model="form" :rules="rules" ref="refForm" label-width="100px">
      <el-form-item label="广告有效期:" prop="time">
        <el-date-picker
          v-model="form.time"
          class="filter-item"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="显示端:" prop="showClient">
        <el-radio-group v-model="form.showClient" @change="changeClient">
          <el-radio v-for="(item,index) in  consts.DEVICE_TYPE_ACTIVE" :key="index" :label="item.value" >{{item.title}}</el-radio>
        </el-radio-group>
        <!-- <checkbox-all v-model="form.showClient" :check-list="consts.DEVICE_TYPE_ACTIVE"></checkbox-all> -->
      </el-form-item>
      <el-form-item label="广告类型:" prop="bannerType">
        <el-radio-group v-model="form.bannerType" >
          <el-radio v-for="(item,index) in  consts.AD_BANNER_TYPE" :key="index+'e'" :label="item.value" >{{item.title}}</el-radio>
        </el-radio-group>
        <!-- <checkbox-all v-model="form.showClient" :check-list="consts.DEVICE_TYPE_ACTIVE"></checkbox-all> -->
      </el-form-item>
      <el-form-item label="广告位置:" prop="position">
        <el-select v-model="form.position" :disabled="isDisableAdPosition">
          <el-option v-for="item in consts.BANNER_TYPE"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value"
                     v-if="item.type === form.showClient || item.key === form.showClient"
          >
          </el-option>
        </el-select>
        <!-- <el-cascader
          :options="consts.BANNER_TYPE"
          :show-all-levels="false"
          v-model="form.wholePosition"
          @change="handleChange">
        </el-cascader> -->
      </el-form-item>

      <el-form-item label="广告名称:" prop="name">
        <el-input type="textarea" :rows="1" class="article-textarea" autosize
                  v-model="form.name">
        </el-input>
      </el-form-item>

      <!--<el-form-item label="显示端:" prop="showClient">-->
      <!--<el-select v-model="form.showClient" placeholder="请选择显示端" :multiple="true">-->
      <!--<el-option v-for="item in consts.DEVICE_TYPE_ACTIVE"-->
      <!--v-if="item.value !== -1"-->
      <!--:key="item.value"-->
      <!--:label="item.title"-->
      <!--:value="item.value">-->
      <!--</el-option>-->
      <!--</el-select>-->
      <!--</el-form-item>-->

      <!--<el-form-item label="显示端:" prop="showClient">-->
      <!--<checkbox-all :check-list="consts.DEVICE_TYPE" v-model="form.showClient"></checkbox-all>-->
      <!--</el-form-item>-->
      <el-row>
        <el-col :sm="12">
          <el-form-item label="广告图:" prop="image">
            <img :src="form.image" v-if="form.image" class="image"/>
            <editor-image color="#1890ff" class="editor-upload-btn"
                          :limit="1"
                          @successCBK="imageSuccessCBK"></editor-image>
          </el-form-item>
        </el-col>
        <el-col  :sm="12">
          <el-form-item label="缩略图:" prop="smallImage">
            <img :src="form.smallImage" v-if="arr.length>0" class="image"/>
            <editor-image color="#1890ff" v-model="form.smallImage" class="editor-upload-btn"
                          :limit="1" @successCBK="smallImageSuccessCBK"></editor-image>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="mp4:" prop="video">
        <input :value="form.video" v-if="form.video" type="hidden" />
        <editor-video color="#1890ff" class="editor-upload-btn"
                      :limit="1"
                      :video="form.video"
                      v-model="form.video"

                      @successCBK="videoSuccessCBK"></editor-video>
      </el-form-item>
      <el-form-item label="内容编辑" v-show="isShowText">
        <el-tip>注1:链接优先级高于文本内容，若是同时填写了链接和文本内容，用户在前台点击banner图则跳转链接，若是没有填写链接只填写了文本则弹窗文本内容</el-tip>
        <el-tip>注2:文本内容编辑只支持"首页-banner"</el-tip>
      </el-form-item>
      <el-form-item  label="链接地址" :prop="'actionUrl'+testByActionUrl"  >
        <el-input type="textarea" :rows="1" class="article-textarea" autosize  placeholder="请输入链接地址"
                  v-model="form.actionUrl">
        </el-input>
        <el-tip >提示：内链直接填路径名，外链加http:// （http://），空链可不填。 </el-tip><!--填写即为跳转专题页活动。-->
      </el-form-item>
      <el-form-item  label="赛事ID" prop="matchId" v-if="isShowMatchId" >
        <el-select v-model="form.matchId" clearable>
          <el-option v-for="(item,index) in matchTypeArr" :value="item.id" :key="index+'e'" :label="item.sportName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主题" prop="theme" v-show="isShowText" >
        <el-input  type="textarea" :rows="1"   class="article-textarea" autosize placeholder="请输入主题"
                   v-model="form.theme" maxlength="20" >
        </el-input>
      </el-form-item>
      <el-form-item label="简介" prop="summary" v-show="isShowText" >
        <el-input type="textarea" :rows="1" class="article-textarea" autosize placeholder="请输入简介"
                  v-model="form.summary" maxlength="30" >
        </el-input>
      </el-form-item>
      <el-form-item label="内容:" prop="content" v-show="isShowText" >
        <Tinymce :height="400" ref="editor" v-model="form.content"/>
        <!--<weditor ref="editor" v-model="form.content"></weditor>-->
        <el-tip >建议300字</el-tip>
      </el-form-item>
      <el-button v-loading="loading" style="margin-left: 10px;" type="primary"
                 @click.native="toSave">确定
      </el-button>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce';
import EditorImage from '@/components/Tinymce/components/editorImage';
import EditorVideo from '@/components/Tinymce/components/editorVideo';

import {
  marketingAdvertisementSaveApi as saveApi,
} from '@/services/api/marketing';

import { form, factory } from '@/build';
import CheckboxAll from '@/components/CheckboxAll/index';
import { MATCH_TYPE } from './matchId';

export default {
  name: 'advertising-edit',
  components: {
    CheckboxAll,
    Tinymce,
    EditorImage,
    EditorVideo,
  },

  mixins: [form],

  props: ['id', 'rowData'],
  data() {
    return {
      src: '',
      arr: [],
      isIndeterminate: true,
      selectAll: false,
      showClientSelect: 0,
      isShowText: false,
      istap: true,
      form: {
        id: this.id,
        time: undefined,
        showClient: 0,
        bannerType: 0,
        matchId: '',
        name: undefined,
        actionUrl: undefined,
        position: undefined,
        image: undefined,
        smallImage: undefined,
        video: undefined,
        theme: undefined, // 主题
        summary: undefined, // 简介
        content: undefined, // 内容
      },
      matchTypeArr: MATCH_TYPE,
      isDisableAdPosition: false, // 是否禁用广告位置下拉框
      isShowMatchId: false, // 是否显示赛似id输入栏
      rules: {
        showClient: { required: true, message: '显示端必须选择' },
        bannerType: { required: true, message: '广告类型必须选择' },
        position: { required: true, message: '广告位置必须选择' },
        name: { required: true, message: '广告主题必须填写' },
        image: { required: true, message: '广告图为必填' },
        time: { type: 'array', required: true, message: '发布时间必须填写' },
        actionUrl: { required: true, message: '链接地址必须填写' },
        // theme: { required: true, message: '主题不能为空' },
        // summary: { required: true, message: '简介不能为空' },
        // content: { required: true, message: '内容不能为空' },
        matchId: { required: true, message: '赛事ID不能为空' },
        // actionUrl: factory.getRule('uri'),
      },
      // testByActionurl: '',
      testByActionUrl: 'q',
    };
  },
  watch: {
    'form.position': {
      handler(newVal) {
        if (newVal === 1) {
          this.isShowText = true;
        } else {
          this.isShowText = false;
        }
      },
    },
    'form.bannerType': {
      handler(newVal) {
        if (newVal === 1) {
          this.form.position = 1;
          this.isDisableAdPosition = true;
          this.testByActionUrl = '';
        } else {
          this.isDisableAdPosition = false;
          this.isShowMatchId = false;
          this.form.mathcId = undefined;
          this.testByActionUrl = 'q';
        }
        if (newVal === 1 && this.form.showClient !== 0) {
          this.isShowMatchId = true;
        } else {
          this.isShowMatchId = false;
        }
      },
    },
    'form.showClient': {
      handler(newVal) {
        if (newVal !== 0 && this.form.bannerType === 1) {
          this.isShowMatchId = true;
        } else {
          this.isShowMatchId = false;
        }
      },
    },
    // 'form.actionUrl': {
    //   handler(newVal) {
    //     if (!newVal && this.form.position === 1) {
    //       this.testByActionurl = '';
    //     } else {
    //       this.testByActionurl = '1';
    //     }
    //   },
    // },
  },
  methods: {
    toSave() {
      // if (!this.istap) { return; }
      this.istap = false;
      // if (!this.form.actionUrl && this.form.position === 1) {
      //   if (!this.form.theme) {
      //     this.error1 = '请填写主题';
      //     return;
      //   }
      //   if (!this.form.summary) {
      //     this.error2 = '请填写简介';
      //     return;
      //   }
      //   if (!this.form.content) {
      //     this.error3 = '请填写内容';
      //     return;
      //   }
      // }

      this.doSave({
        action: 'saveForm',
        form: {
          name: 'refForm',
          scrollToError: true,
        },
      });
    },
    changeClient(val) {
      // if (val === 2 && this.form.position < 7) {
      //   this.form.position = undefined;
      // } else if (val < 2 && this.form.position >= 7) {
      //   this.form.position = undefined;
      // }
      if (this.form.bannerType === 1) {
        this.form.position = 1;
      } else {
        this.form.position = undefined;
      }
    },
    handleChange(value) {
      if (value && value.length === 2) {
        this.form.position = value[1];
      }
    },
    imageSuccessCBK(arr) {
      arr.forEach((picInfo) => {
        this.form.image = picInfo.url;
      });
    },
    smallImageSuccessCBK(arr) {
      this.arr = arr;
    },
    videoSuccessCBK(video) {
      this.form.video = video.responseUrl || null;
    },

  },
  mounted() {
    if (!_.isUndefined(this.rowData)) {
      const {
        showClientArray, startTime, endTime, matchId,
      } = this.rowData;
      this.form = {
        ...this.rowData,
        time: [moment(startTime).format('YYYY-MM-DD HH:mm:ss'), moment(endTime).format('YYYY-MM-DD HH:mm:ss')],
        showClient: showClientArray[0],
        matchId: matchId === 0 ? '' : matchId,
      };
      this.arr.push(this.form.smallImage);
    }


    this.bindSave(saveApi, 'saveForm', 'form', {
      beforeSend: (data) => {
        const {
          showClient, time, smallImage, content, video,
        } = data;
        let startTime; let endTime; let
          smallImageUrl;
        if (!_.isUndefined(time) && _.isArray(time)) {
          startTime = time[0];
          endTime = time[1];
        }
        if (!_.isUndefined(smallImage) && _.isArray(smallImage)) {
          smallImageUrl = smallImage[0];
        } else {
          smallImageUrl = smallImage;
        }
        const reg = /img class="wscnph" src="api/g;
        let newContent = '';
        if (content) {
          newContent = content.replace(reg, 'img class="wscnph" src="/api');
        }
        return {
          ...data,
          video,
          showClient,
          startTime,
          endTime,
          smallImage: smallImageUrl,
          content: newContent,
        };
      },
      afterSuccess: () => {
        this.istap = true;
        this.resetForm('refForm');
        this.form.content = '';
        this.$emit('on-success');
        if (!this.form.id) {
          this.$router.push({
            name: 'marketing-ad',
            replace: true,
            query: {
              tab: 'one',
            },
          });
          localStorage.setItem('freshlist', true);
          this.$refs.refForm.resetFields();
        }
      },
      afterFail: () => {
        this.istap = true;
      },
    });
  },
};
</script>

<style lang="scss" scoped>
  .image {
    width: 100px;
    height: 100px;
  }
</style>
